<template>
  <div class="files-section">
    <div class="files-header">
      <div class="files-header-content">
        <h2 class="files-title">
          <svg
            class="files-icon"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z"
            />
          </svg>
          文件列表 ({{ files.length }} 个文件)
        </h2>
        <button
          :disabled="loading"
          class="refresh-button"
          @click="$emit('refresh')"
        >
          刷新
        </button>
      </div>
    </div>

    <div v-if="loading" class="loading-state">加载中...</div>

    <div v-else-if="files.length === 0" class="empty-state">
      暂无文件，请上传文件开始分享
    </div>

    <div v-else class="overflow-x-auto">
      <table class="min-w-full">
        <thead class="table-header">
          <tr>
            <th class="table-header-cell">文件名</th>
            <th class="table-header-cell">大小</th>
            <th class="table-header-cell">上传时间</th>
            <th class="table-header-cell">操作</th>
          </tr>
        </thead>
        <tbody class="table-body">
          <tr v-for="file in files" :key="file.filename" class="table-row">
            <td class="table-cell">
              <div class="file-name-container" @click="previewFile(file)">
                <svg
                  class="file-type-icon"
                  fill="currentColor"
                  viewBox="0 0 20 20"
                >
                  <path
                    fill-rule="evenodd"
                    d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z"
                    clip-rule="evenodd"
                  />
                </svg>
                <span class="file-name">{{ file.filename }}</span>
              </div>
            </td>
            <td class="table-cell">
              {{ formatFileSize(file.size) }}
            </td>
            <td class="table-cell">
              {{ formatDateTime(file.uploadTime) }}
            </td>
            <td class="table-cell">
              <button
                class="download-btn"
                :disabled="downloading === file.filename"
                @click="downloadFile(file.filename)"
              >
                下载
              </button>
              <button
                :disabled="deleting === file.filename"
                class="delete-btn"
                @click="deleteFile(file.filename)"
              >
                {{ deleting === file.filename ? "删除中..." : "删除" }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";

// Props
defineProps({
  files: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
});

// Emits
const emit = defineEmits(['refresh', 'download-success', 'download-error', 'delete-success', 'delete-error', 'preview-file']);

// Reactive data
const downloading = ref("");
const deleting = ref("");

// Format file size
const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// Format date time
const formatDateTime = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN");
};

// Download file with multiple fallback methods
const downloadFile = async (filename) => {
  downloading.value = filename;
  try {
    // Try different download methods based on browser capabilities
    await downloadWithBlobMethod(filename);
  } catch (blobError) {
    console.warn("Blob download failed, trying direct link method:", blobError);
    try {
      await downloadWithDirectLink(filename);
    } catch (directError) {
      console.error("All download methods failed:", directError);
      $emit('download-error', `下载失败: ${directError.message}`);
    }
  } finally {
    downloading.value = "";
  }
};

// Method 1: Fetch + Blob approach (recommended for better control)
const downloadWithBlobMethod = async (filename) => {
  const response = await fetch(
    `/api/lan-share/${encodeURIComponent(filename)}`
  );

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  const blob = await response.blob();
  const url = window.URL.createObjectURL(blob);

  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  link.style.display = "none";

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);

  $emit('download-success', `文件 "${filename}" 下载成功`);
};

// Method 2: Direct link approach (fallback for restricted environments)
const downloadWithDirectLink = async (filename) => {
  // Check if file exists first
  const checkResponse = await fetch(
    `/api/lan-share/${encodeURIComponent(filename)}`,
    { method: "HEAD" }
  );
  if (!checkResponse.ok) {
    throw new Error(`文件不存在或无法访问`);
  }

  // Use window.open as fallback
  const downloadUrl = `/api/lan-share/${encodeURIComponent(filename)}`;
  const newWindow = window.open(downloadUrl, "_blank");

  // If popup was blocked, try direct navigation
  if (
    !newWindow ||
    newWindow.closed ||
    typeof newWindow.closed === "undefined"
  ) {
    // Fallback: direct navigation (may replace current page)
    window.location.href = downloadUrl;
  }

  $emit('download-success', `正在下载文件 "${filename}"...`);
};

// Preview file
const previewFile = (file) => {
  emit('preview-file', file);
};

// Delete file
const deleteFile = async (filename) => {
  if (!confirm(`确定要删除文件 "${filename}" 吗？`)) return;

  deleting.value = filename;
  try {
    const response = await $fetch("/api/lan-share", {
      method: "POST",
      body: {
        action: "delete",
        filename,
      },
    });

    if (response.success) {
      $emit('delete-success', "文件删除成功");
    }
  } catch (error) {
    console.error("Delete error:", error);
    $emit('delete-error', "删除失败: " + (error.data?.message || error.message));
  } finally {
    deleting.value = "";
  }
};
</script>

<style scoped>
.files-section {
  background: white;
  border-radius: 16px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.files-header {
  padding: 30px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.files-header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.files-title {
  font-size: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
  color: #1d1d1f;
  letter-spacing: -0.01em;
}

.files-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
  color: #6e6e73;
}

.refresh-button {
  background: rgba(0, 122, 255, 0.1);
  color: #007aff;
  border: none;
  padding: 8px 16px;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
}

.refresh-button:hover:not(:disabled) {
  background: rgba(0, 122, 255, 0.2);
  transform: translateY(-1px);
}

.refresh-button:disabled {
  background: rgba(142, 142, 147, 0.1);
  color: #8e8e93;
  cursor: not-allowed;
  transform: none;
}

.loading-state,
.empty-state {
  padding: 60px;
  text-align: center;
  color: #8e8e93;
  font-size: 15px;
}

.table-header {
  background: rgba(0, 0, 0, 0.02);
}

.table-header-cell {
  padding: 16px 24px;
  text-align: left;
  font-size: 12px;
  font-weight: 600;
  color: #6e6e73;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.table-body {
  background: white;
}

.table-row {
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  transition: background-color 0.2s ease;
}

.table-row:hover {
  background: rgba(0, 0, 0, 0.02);
}

.table-cell {
  padding: 16px 24px;
  color: #1d1d1f;
  font-size: 14px;
  vertical-align: middle;
}

.file-name-container {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 6px;
  padding: 4px 8px;
  margin: -4px -8px;
}

.file-name-container:hover {
  background: rgba(0, 122, 255, 0.1);
}

.file-type-icon {
  width: 16px;
  height: 16px;
  margin-right: 12px;
  color: #6e6e73;
}

.file-name {
  font-weight: 500;
  color: #1d1d1f;
  transition: color 0.2s ease;
}

.file-name-container:hover .file-name {
  color: #007aff;
}

.download-btn,
.delete-btn {
  padding: 6px 12px;
  border-radius: 6px;
  border: none;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-right: 8px;
}

.download-btn {
  background: rgba(0, 122, 255, 0.1);
  color: #007aff;
}

.download-btn:hover:not(:disabled) {
  background: rgba(0, 122, 255, 0.2);
  transform: translateY(-1px);
}

.delete-btn {
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}

.delete-btn:hover:not(:disabled) {
  background: rgba(255, 59, 48, 0.2);
  transform: translateY(-1px);
}

.download-btn:disabled, 
.delete-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  transform: none;
}

.overflow-x-auto {
  overflow-x: auto;
}

.min-w-full {
  min-width: 100%;
}
</style> 